package com.ai_daily.aitiantian.api;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class StreamRequestTest {
    public static void main(String[] args) throws IOException {
        Gson gson = new Gson();
        MediaType mediaType = MediaType.parse("application/json");
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("androidId", "50306d21a7573e49");
        requestMap.put("question", "什么是精分人格？");
        RequestBody body = RequestBody.create(mediaType, gson.toJson(requestMap));
        long time0 = System.currentTimeMillis();
        Request request = new Request.Builder()
                .url("http://tiantianai.ai-daily.com.cn/aiChat/chat_v3")
                .method("POST", body)
                .header("Accept", "text/event-stream")
                .build();
        Response response =SeeOkHttpClientManager.INSTANCE.getOkHttpClient().newCall(request).execute();
        // 记录上一次接收消息的时间
        long lastReceivedTime = System.currentTimeMillis();
        if (response != null) {
            InputStream stream = response.body().byteStream();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    // 跳过注释或空行
                    if (line.isEmpty() || line.startsWith(":")) {
                        continue;
                    }
                    // 计算时间间隔
                    long currentTime = System.currentTimeMillis();
                    long interval = currentTime - lastReceivedTime;
                    System.out.println("时间间隔--------" + interval + " ms");
                    lastReceivedTime = currentTime;

                    // 处理每一行数据，这里可以解析 SSE 格式的消息
                    if (line.startsWith("data: ")) {
                        // 提取数据部分
                        String data = line.substring(6).trim();
                        System.out.println("Received data: " + data);
                    } else if (line.startsWith("event: ")) {
                        // 处理事件名称
                        String event = line.substring(7).trim();
                        System.out.println("Received event: " + event);
                    } else if (line.startsWith("id: ")) {
                        // 处理事件ID
                        String id = line.substring(4).trim();
                        System.out.println("Received id: " + id);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
